package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.Class;
import com.easyattendance.model.ClassUser;
import com.easyattendance.model.Teacher;
import com.easyattendance.services.AddClassService;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.ValidationsService;
import com.easyattendance.util.SecurePassword;


@WebServlet("/AddClassServlet")
public class AddClassServlet extends HttpServlet {
	
	private static final long serialVersionUID = -7762891816040801568L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
    	 
		 response.setContentType("text/html;charset=UTF-8");
		 String actionType = request.getParameter("action_type");
		 boolean createDispatcherFlag = false;
		 boolean updateDispatcherFlag = false;
		 
		 AddClassService addClassService = new AddClassService();
		 AddTeacherService addTeacherService = new AddTeacherService();
		 AddSectionService addSectionService = new AddSectionService();
		 ValidationsService validationsService = new ValidationsService();
		 int noOfElectives = -1;
		 
		 if(actionType.equals("create")) {
			String classId = null;
			String className = request.getParameter("class_name");			
			String division=request.getParameter("select_division");
			String studEmail = request.getParameter("stud_email");
			String studPassword = request.getParameter("stud_password");
			String studRepassword = request.getParameter("stud_repassword");
			if(!request.getParameter("no_of_electives").isEmpty()){
				noOfElectives = Integer.parseInt(request.getParameter("no_of_electives"));
			}
				
			String term_type=request.getParameter("select_term_type");
			Teacher classTeacher=null;
			String teacherName = request.getParameter("teacher_name");
			
			if(className.isEmpty() || division.isEmpty() || studEmail.isEmpty() || studPassword.isEmpty() || studRepassword.isEmpty() || noOfElectives < 0 || term_type.isEmpty() || teacherName.isEmpty()){
		        	request.setAttribute("null_values", "All * fields are required");
		        	createDispatcherFlag = true;
	        }else{
	        	
	        	String validateName = validationsService.validateName(className);
		        String validateEmail = validationsService.validateEmailId(studEmail);
		        String validatePassword = validationsService.validatePassword(studPassword);
		        boolean validateBothPasswords = validationsService.validateBothPasswords(studPassword, studRepassword);
		        
		        if(validateName.equals("Correct")) {
		        	if(validateEmail.equals("Correct")) {
		        		if(validatePassword.equals("Correct") && validateBothPasswords) {
		        			
		        			if(term_type.equals("Year"))
		        			{   classId=className+"-"+division;
		        				className=className+"-"+division;
		        			}
		        			else if(term_type.equals("Semester"))
		        			{
		        				 classId=className+"-"+division;
		        				 className=className+"-"+division;
		        			}
		        			
		        			Class newClass = new Class(classId);
		        			boolean res = addClassService.ifAlreadyExists(newClass);		        			
		        			boolean teacherExists= addTeacherService.ifAlreadyExists(teacherName);
		        			
		        			boolean result=false;
		        			
		        			if (!res) {
		        				if (teacherExists) {
		        					classTeacher = addTeacherService.getTeacherByTeacherName(teacherName);
		        					Class class1 = new Class(classId, className, noOfElectives,	division,term_type, classTeacher.getTeacher_id());
		        					
		        					String currentUser = (String) request.getSession().getAttribute("currentUser");
		        					class1.setSection(addSectionService.getSectionBySectionEmail(currentUser));
		        		
		        					ClassUser classUser = new ClassUser(classId, studEmail, SecurePassword.getHashValue(studPassword));
		        					classUser.setClassObj(class1);
		        					result = addClassService.addClass(class1, classUser);
		        				} else {
		        					request.setAttribute("teacherExists", "Teacher already exists.");
		        					createDispatcherFlag = true;
		        				}
		        			
		        			} else {
		        				request.setAttribute("classExists", "Class already exists.");
		        				createDispatcherFlag = true;
		        			}
		        				
	        				if (result) {
	        					addTeacherService.updateTeacherToClassTeacher(classTeacher);
	        					request.setAttribute("classAdded", "Class added successfully.");
	        					createDispatcherFlag = true;
	        					
	        				} else {
	        					
	        					request.setAttribute("classNotAdded", "Class not added.");
	        					createDispatcherFlag = true;
	        		        	
	        				}
		        			
		        		}
		        		else {//validate password
		        			request.setAttribute("validate_class_passwords", "Password not valid or Passwords do not match.");
				        	createDispatcherFlag = true;
		        		}
		        	}
		        	else {//validate email
		        		request.setAttribute("validate_class_email", validateEmail);
			        	createDispatcherFlag = true;
		        	}
		        }
		        else {//validate name
		        	request.setAttribute("validate_class_name", validateName);
		        	createDispatcherFlag = true;
		        }
		    }//main else - of empty conditions
			
			//Common error print and redirect.
			if(createDispatcherFlag) {
				RequestDispatcher rd = request.getRequestDispatcher("views/section/addClass.jsp");
		    	rd.forward(request, response);
			}
			
				
		 }
		 else if (actionType.equals("update")) {
			int i = Integer.parseInt(request.getParameter("i_value"));
			 
			String studEmail = request.getParameter("common_student_id"+i);
			//String studPassword = request.getParameter("common_student_pwd"+i);
			noOfElectives = Integer.parseInt(request.getParameter("class_elective_no"+i));
			String classTeacherId = request.getParameter("teacher_select"+i);
			String classId = request.getParameter("class_id"+i);
			
			/* @author rohan
			 * Dont delete.
			 */
			/*if(studEmail.isEmpty() || noOfElectives < 0 || classTeacherId.isEmpty()){
	        	request.setAttribute("null_values", "All fields are required");
	        	createDispatcherFlag = true;
			}*/
			
			
			Class classs = addClassService.getClassById(classId);
			classs.setNo_of_electives(noOfElectives);
			
			if(!classTeacherId.isEmpty()) {
				//Remove existing class teacher from being class teacher
				Teacher classTeacher = addTeacherService.getTeacherById(classs.getClass_teacher_id());
				addTeacherService.removeTeacherAsClassTeacher(classTeacher);
				
				// Add the new teacher as class teacher
				classTeacher = addTeacherService.getTeacherById(classTeacherId);
				addTeacherService.updateTeacherToClassTeacher(classTeacher);
				classs.setClass_teacher_id(classTeacherId);
			}
			ClassUser classUser = addClassService.getClassUserById(classId);
			classUser.setEmail_id(studEmail);
			//classUser.setPassword(studPassword);
			
			boolean result1 = addClassService.updateClass(classs, classUser);
			
			if(result1) {
				 //out.println("Class updated successfully");
				request.setAttribute("classUpdated", "Class updated successfully.");
				updateDispatcherFlag = true;
			}
			else {
				//out.println("Class NOT updated successfully");
				request.setAttribute("classNotUpdated", "Class not updated successfully.");
				updateDispatcherFlag = true;
			}
			if(updateDispatcherFlag) {
				RequestDispatcher rd = request.getRequestDispatcher("views/section/classSettings.jsp");
		    	rd.forward(request, response);
			}
			
		 }
		 else if(actionType.equals("delete")) {
				int i = Integer.parseInt(request.getParameter("i_value"));
				String classId = request.getParameter("class_id"+i);
				//Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
				Class classs = addClassService.getClassById(classId);
				
				//Remove existing class teacher from being class teacher
				Teacher classTeacher = addTeacherService.getTeacherById(classs.getClass_teacher_id());
				addTeacherService.removeTeacherAsClassTeacher(classTeacher);
				
				boolean res = addClassService.deleteClass(classId);
				
				if(res){
					//out.println("Class deleted successfully");
					
					request.setAttribute("classDeleted", "Class deleted successfully.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/section/classSettings.jsp");
		        	rd.forward(request, response);
				}
				else {
					//out.println("Class CANNOT be deleted successfully");
					request.setAttribute("classNotDeleted", "Class not deleted.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/section/classSettings.jsp");
		        	rd.forward(request, response);
				}
			}
		 else {
			 //out.println("Invalid Choice.. Go Back and choose again");
			request.setAttribute("invalidChoice", "Invalid Choice.. Go Back and choose again.");
        	RequestDispatcher rd = request.getRequestDispatcher("views/section/classSettings.jsp");
        	rd.forward(request, response);
		 }
		 
        
    }

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
